<template>
  <div class="flex-center h-full">
    <el-form ref="ruleFormRef" style="width: 400px" :model="loginForm" status-icon label-width="auto">
      <el-form-item label="用户" prop="userName">
        <el-input v-model="loginForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="验证码" prop="code" :required="true">
        <div class="flex-center w-full">
          <el-input auto-complete="off" size="large" class="flex-1" v-model="loginForm.code" autocomplete="off" placeholder="请输入验证码" />
          <el-image @click="getCaptcha" :src="codeUrl" class="h-10 cursor-pointer rounded-1.5" />
        </div>
      </el-form-item>
      <div class="flex-center">
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { type FormInstance } from 'element-plus'
import LoginApi from '@/api/module/login'
import { useUserStore } from '@/stores'
import router from '@/router'
import { LocationQuery, useRoute } from 'vue-router'
const ruleFormRef = ref<FormInstance>()
const codeUrl = ref('')
const route = useRoute()
const userStore = useUserStore()
const loginForm = reactive({
  password: 'admin',
  userName: 'admin',
  code: '0'
})

/**
 * 获取验证码
 */
const getCaptcha = async () => {
  const res = await LoginApi.getCodeImg()
  if (res.code === 200) {
    const img = res.data.img
    if (img.indexOf('data:image') > -1) {
    } else {
      codeUrl.value = 'data:image/png;base64,' + img
    }
  }
}

/**
 * 提交表单
 *
 * @param formEl 表单
 */
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      userStore.userLogin({ ...loginForm }).then(res => {
        if (res.code === 200) {
          const { path, queryParams } = parseRedirect()
          router.push({ path: path, query: queryParams })
          ElMessage.success('提交成功')
        }
      })
    } else {
    }
  })
}

/**
 * 重置表单
 *
 * @param formEl 表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const parseRedirect = () => {
  const query: LocationQuery = route.query
  const redirect = (query.redirect as string) ?? '/home'
  const url = new URL(redirect, window.location.origin)
  const path = url.pathname
  const queryParams: Record<string, string> = {}
  url.searchParams.forEach((value, key) => {
    queryParams[key] = value
  })

  return { path, queryParams }
}

onMounted(() => {
  getCaptcha()
})
</script>
